package com.heima.filter;

import cn.hutool.core.util.StrUtil;
import com.heima.utils.common.HutoolJWT;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 全局过滤器
 * @author chenshan
 */
@Component
public class AdminLoginAuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应
        ServerHttpResponse response = exchange.getResponse();

        // 路径的排除
        if (StrUtil.contains(request.getURI().getPath(), "login/in")) {
            // 不需要做登录校验 直接放行
            return chain.filter(exchange);
        }

        // 从请求头中获取Token
        String token = request.getHeaders().getFirst("token");

        // 判断Token是否有效
        if (StrUtil.isNotBlank(token) && HutoolJWT.verifyToken(token)) {
            // 获取Token中的数据并且保存到Request对象头中
            Map<String, Object> map = HutoolJWT.parsedToken(token);
            String id = StrUtil.toString(map.get("id"));
            request.mutate().headers(httpHeaders -> httpHeaders.add("id", id));
            exchange.mutate().request(request);
            // 把解析后的Token保存到Request对象后进行放行
            return chain.filter(exchange);
        }

        // Token为空 或者 Token解析失败
        // 给页面返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
